package net.avcompris.base.testutil.processes;

import static com.google.common.collect.Iterables.toArray;
import static org.apache.commons.lang3.StringUtils.isBlank;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.ArrayUtils;

abstract class ExtractAllScmIgnoresProcessXXX extends
		AbstractProcess<ScmIgnore, ScmIgnore[]> {

	protected ExtractAllScmIgnoresProcessXXX(final String... projectNames) {

		this.projectNames = projectNames;
	}

	private final String[] projectNames;

	@Override
	public final void execute() throws Exception {

		// 1. LOAD IGNORE FILES

		for (final File f : new File("src/test/samples/workspace-001")
				.listFiles()) {

			if (f.isDirectory() && !f.getName().startsWith(".")
					&& ArrayUtils.contains(projectNames, f.getName())) {

				final List<String> i = new ArrayList<String>();

				final boolean isSvn;

				final boolean isHg;

				final File svnFile = new File(f, "svn-dir-prop-base");

				final File hgFile = new File(f, "hg-ignore");

				if (svnFile.exists()) {

					isSvn = true;

					boolean inSvnIgnore = false;

					final List<String> lines = FileUtils.readLines(svnFile);
					for (final String line : lines) {
						final String t = line.trim();
						if (!inSvnIgnore) {
							if (t.equals("svn:ignore")) {
								inSvnIgnore = true;
							}
						} else {
							if (t.equals("END")) {
								break;
							} else if (!isBlank(t) && !t.startsWith("V ")) {
								i.add(t);
							}
						}
					}

				} else {

					isSvn = false;
				}

				if (hgFile.exists()) {

					isHg = true;

					final List<String> lines = FileUtils.readLines(hgFile);

				} else {

					isHg = false;
				}

				final ScmIgnore current = new ScmIgnore(f.getName(), isSvn,
						isHg, i);

				setCurrent(current);

				ignores.add(current);
			}
		}
	}

	private final List<ScmIgnore> ignores = new ArrayList<ScmIgnore>();

	@Override
	public final ScmIgnore[] getResult() {

		return toArray(ignores, ScmIgnore.class);
	}
}
